var chat = {
	el:{},
	env:{ index:0, url:{ 'stream':'/get', "add":"/add" } },
	init:function(){
		with(chat){
			el.message = new pi.element( pi.get("message") );
			el.name = new pi.element( pi.get("name") );
			el.message.event.addListener("keyup",function(_event){
				with(chat){
					if(_event.keyCode!=13)
						return;
					send( el.message.environment.getElement().value, el.name.environment.getElement().value );
					el.message.update("");
				}
			});
			stream();
			pi.util.AddEvent(window,'resize',scroll);
		}
	},
	stream:function(){
		with(chat){
			env.comet = pi.comet.get(env.url.stream+(env.url.stream.search("\\?")==-1?"?":"&")+"index="+env.index,read);
			setTimeout(stream,10000);
		}
	},
	read:function(_response){
		with(chat){
			var data = [];
			eval(_response);
			for (var i = 0; i < data.length; i++) {
				env.index = data[i].unixtime;
				new pi.element("div").update("<strong>{0} :</strong>{1}".format(data[i].name,data[i].message)).insert(pi.get("data"));
			};
			scroll();
		}
	},
	send:function(_message,_name){
		with(chat){
			var req = new pi.xhr(env.url.add).environment.
			addData("message",escape(_message)).environment.
			addData("name",escape(_name)).environment.
			setType("POST").environment.
			setAsync(false).
			send();
		}
	},
	scroll:function(){
		with(chat){
			if( (pi.get("data_c").offsetHeight-pi.get("data").offsetHeight-50) <0 )
				pi.get("data").style.marginTop = (pi.get("data_c").offsetHeight-pi.get("data").offsetHeight-50)+"px"
		}
	}
};

pi.util.Init.push(chat.init);
